<?php
$GLOBALS['INC_LOG']	=	1;

class Log
{
	/**
	 * This array item: array(filename, log content...)
	 *
	 */
	static $content	=	array();
	
	static function active($log)
	{
		self::$content[]	=	array('active_'.date('Ymd').'.log', $log);
	}
	
	static function error($log)
	{
		$e	=	new ErrorException($log);
		self::$content[]	=	array('error_'.date('Ymd').'.log', ''.$e);
		unset($e);
	}
	
	static function sql($log)
	{
		self::$content[]	=	array('log_'.date('Ymd').'.log', $log);
	}
	
	static function write($log, $file='common.log')
	{
		self::$content[]	=	array($file, $log);
	}

	/**
	 * sync log file(s)
	 *
	 */
	static function flush()
	{
		static $base;
		if(!$base)
		{
			//Imitate Apache log file format
			$base	=	sprintf("%s %s - - [%%s] \"%s\" \"%%s\"\n", 
						(isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''),
						$_SERVER['REMOTE_ADDR'],
						($_SERVER['REQUEST_METHOD'].' '.$_SERVER['REQUEST_URI'].' '.$_SERVER['SERVER_PROTOCOL'])
					);
		}
		
		//本来这个地方想加个cache(按文件名)，又感觉没必要
		if(self::$content) foreach(self::$content as $log)
		{
			file_put_contents(
				DATA_PATH.'/log/'.$log[0],
				sprintf($base, date('r'), (is_scalar($log[1]) ? $log[1] : self::str($log[1])) ),
				FILE_APPEND
			);
		}
		self::$content	=	array();
	}
	
	/**
	 * 替代 print_r(xx,true)的用法。
	 * 因为print_r取返回值的方法是用到ob_buffer，在自定义的ob_handler里会出错
	 */
	static function str($o, $lv=0)
	{
		if(is_object($o))
			$o	=	get_object_vars($o);
		if(is_array($o))
		{
			$head	=	str_repeat("\t", $lv);
			$tmp	=	"array (\n";
			foreach($o as $k=>$v)
			{
				$tmp	.=	("{$head}\t[$k]\t=>  ".self::str($v, $lv+1)."\n");
			}
			return $tmp."$head)";
		}
		else 
		{
			return $o;
		}
	}
	
}

?>